package br.com.dallasmotopecas.util.model;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import br.com.dallasmotopecas.util.validacao.ValidarObjeto;

public abstract class AbstractModel
{
	private Connection connection;

	protected Connection getConnection()
	{
		return connection;
	}

	protected void setConnection(Connection connection)
	{
		this.connection = connection;
	}
	
	public AbstractModel(Connection connection)
	{
		setConnection(connection);
	}
	
	protected void close(PreparedStatement ps)
	{
		try
		{
			if (ps != null)
			{
				ps.close();
			}
		}
		catch(SQLException e)
		{
			e.printStackTrace();
		}
		finally
		{
			if (ps != null)
				ps = null;
		}
	}

	protected void close(PreparedStatement ps, ResultSet rs)
	{
		try
		{
			if (ps != null && rs != null)
			{
				ps.close();
				rs.close();
			}
		}
		catch(SQLException e)
		{
			e.printStackTrace();
		}
		finally
		{
			if (rs != null)
				rs = null;
			
			if (ps != null)
				ps = null;
		}
	}
	
	protected int getIdInsert(String nomeTabela)
	{
		PreparedStatement ps = null;
		ResultSet rs = null;
		int ultimoCodigo = 0;
		try
		{
			if (ValidarObjeto.isStringValida(nomeTabela))
			{
				ps = getConnection().prepareStatement("SELECT LAST_INSERT_ID() AS CODIGO FROM " + nomeTabela + ";");
				rs = ps.executeQuery();
				
				if (rs.next())
				{
					ultimoCodigo = rs.getInt("CODIGO");
				}
				
				return ultimoCodigo;
			}
		}
		catch(SQLException e)
		{
			e.printStackTrace();
		}
		finally
		{
			close(ps, rs);
		}
		return ultimoCodigo;
	}
}
